package com.sky.controller.admin;

import com.sky.dto.CategoryDTO;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品接口")
@Slf4j
public class DishController {


    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String CACHE_TO_DEL_EXCHANGE="cache_del_exchange";
    @PostMapping
    public Result<?> save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品，{}",dishDTO);
        String key="dish_"+dishDTO.getCategoryId().toString();
        //第一次删缓存
        cleanCache(key);
        //写入mysql
        dishService.saveWithFlavor(dishDTO);
        //第二次删缓存
        //cleanCache(key);
        sendCacheDeletionMessage(key);
        return Result.success();

    }
    @GetMapping("page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分类查询，{}",dishPageQueryDTO);
        PageResult pageResult=dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id){
        log.info("根据id查询菜品，{}",id);
        DishVO dishVO=dishService.getById(id);
        return Result.success(dishVO);
    }

    @PutMapping
    public Result<?> update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品：{}", dishDTO);
        dishService.updateWithFlavor(dishDTO);
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        //cleanCache("dish_*");
        sendCacheDeletionMessage("dish_*");
        return Result.success();
    }

    @DeleteMapping
    public Result<?> delete(@RequestParam List<Long> ids){
        log.info("菜品批量删除：{}", ids);
        dishService.deleteBatch(ids);//后绪步骤实现
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        //cleanCache("dish_*");
        sendCacheDeletionMessage("dish_*");
        return Result.success();
    }

    @GetMapping("list")
    public Result<?> getByCategoryId(@RequestParam Long categoryId){
        log.info("根据分类查询菜品：{}",categoryId);
        List<Dish> dishes=dishService.getByCategoryId(categoryId);

        return Result.success(dishes);
    }

    @PostMapping("status/{status}")
    public Result<?> sellOrNot(@PathVariable Integer status,@RequestParam Long id){
        log.info("菜品起售、停售");
        dishService.updateStatus(id,status);
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        //cleanCache("dish_*");
        sendCacheDeletionMessage("dish_*");
        return Result.success();
    }

    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }


    private void sendCacheDeletionMessage(String pattern) {
        rabbitTemplate.convertAndSend(CACHE_TO_DEL_EXCHANGE,"cacheDel", pattern, msg -> {
            msg.getMessageProperties().setHeader("x-retry-count", 0);
            return msg;
        });
    }
}
